import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.junit.Test;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class test {
    @Test
    public void test1() throws IOException, TemplateException {
        //创建配置类
        Configuration configuration = new Configuration(Configuration.getVersion());
        //设置模板所在的路径
        configuration.setDirectoryForTemplateLoading(new File("E:\\ftl"));
        //设置字符集
        configuration.setDefaultEncoding("utf-8");
        //加载模板
        Template template = configuration.getTemplate("a.ftl");
        //创建数据模型
        HashMap map = new HashMap();
        map.put("name1","张三");
        map.put("name2","李四");
        map.put("success",true);


        ArrayList<Map> list = new ArrayList<Map>();
        HashMap map1 = new HashMap();
        map1.put("name","香蕉");
        map1.put("price",20);
        HashMap map2 = new HashMap();
        map2.put("name","苹果");
        map2.put("price",30);
        HashMap map3 = new HashMap();
        map3.put("name","草莓");
        map3.put("price",40);
        list.add(map1);
        list.add(map2);
        list.add(map3);

        map.put("list",list);
        //创建writer对象
        FileWriter out = new FileWriter(new File("e:\\ftl\\test.html"));
        //输出
        template.process(map,out);
        //关闭流
        out.close();
    }

    @Test
    public void test2() throws IOException, TemplateException {
        //获取freemaker配置对象
        Configuration configuration = new Configuration(Configuration.getVersion());
        //设置默认编码
        configuration.setDefaultEncoding("utf-8");
        //设置加载模板的路径
        configuration.setDirectoryForTemplateLoading(new File("E:/ftl"));
        //获取模板对象
        Template template = configuration.getTemplate("b.ftl");
        //创建map
        HashMap map = new HashMap();
        map.put("name","lisi");
        //创建字符输出流
        FileWriter out=new FileWriter("E:/ftl/b.html");
        //创建目标文件并写入
        template.process(map,out);
        //关闭流
        out.close();
    }
}
